package org.rainy.gift.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.apache.commons.lang3.StringUtils;
import org.rainy.gift.domain.User;
import org.rainy.gift.exception.BusinessException;
import org.rainy.gift.exception.ResponseCode;
import org.rainy.gift.exception.RonghuaAssert;
import org.rainy.gift.service.IVerifyCodeService;
import org.rainy.gift.util.SmsUtil;
import org.rainy.gift.util.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.stereotype.Service;

import javax.swing.text.html.parser.Entity;
import java.util.concurrent.TimeUnit;
@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    RedisTemplate redisTemplate;
    /*
    1 参数校验
    1.1判断手机号是否存在：
    创建了一个EntityWrapper<User> 对象，这个对象用于封装对 User 实体类的查询条件就是是否含有这个手机号，将wrapper传入selectOne去查询，无论有多少条查询结果selectOne方法只会返回其中一条记录,断言判空
    存在就报错误信息，不存在发送验证码
    2发送验证码：
    根据key【业务前缀+手机号】获取去Redis中获取当前手机号验证码，
    判断当前验证码是否为空，
    判断用是否过来重发时间，redisTemplate.getExpire(key,单位)来获取过期时间，
    如果过期时间大于4*60那么就生成验证码，并存入redis，key为业务前缀加手机号,并将短信发给用户
    */
    @Override
    public void SendSmsCode(String phone,String keyPrefix) {
        Wrapper<User> wrapper = new EntityWrapper<User>().eq("phone", phone);
        User user = userService.selectOne(wrapper);
        RonghuaAssert.isNull(user, ResponseCode.RESPONSE_CODE_10020);
        String key = keyPrefix + phone;
        System.out.println(keyPrefix+phone+"key");
        String smsCode = (String) redisTemplate.opsForValue().get(key);
        if(StringUtils.isNotBlank(smsCode)){
            Long expire = redisTemplate.getExpire(key,TimeUnit.SECONDS);
            if(expire > 4 *60){
                throw new BusinessException(ResponseCode.RESPONSE_CODE_10021);
            }
        }else {
            smsCode = StrUtils.getRandomString(6);
        }
        redisTemplate.opsForValue().set(key, smsCode);
        String msg = "您的验证码为"+smsCode+",验证码将在5分钟后过期,请尽快填写";
        //SmsUtil.sendSms(dto.getPhone(),msg);
        System.out.println(msg);
    }
    @Override
    public String getSmsCode(String phone,String keyPrefix) {
        String key = keyPrefix+phone;
        String smsCode = (String)redisTemplate.opsForValue().get(key);
        RonghuaAssert.isNotBlank(smsCode,ResponseCode.RESPONSE_CODE_10018);
        return smsCode;
    }
}
